<template>
	<view v-if="aijShow" class="cu-modal bottom-modal show" :style="[{top:'auto'}]">
		<view class="cu-dialog">
			<view class="padding-xl">
				<scroll-view scroll-y="true" class="scroll-y" ref="aij-msgs" :scroll-top="scrollTop">
					<view v-for="msg in aijMsgs" class="content bg-green shadow">
						<rich-text @itemclick="clickMsg" :nodes="msg.msg" class="rich-text"></rich-text>
					</view>
				</scroll-view>
			</view>
			<view class="cu-bar input">
				<view class="action">
					<text class="cuIcon-unfold text-grey" @click="msgFold"></text>
				</view>
				<input class="solid-bottom" 
					maxlength="300"
					cursor-spacing="10"
					:adjust-position="false"
					:focus="aijChat.focus"
					@focus="inputFocus"
					@blur="inputBlur"
					v-model="aijChat.msg" 
					:password="aijChat.password"
					:placeholder="aijChat.placeholder"
					:refer="aijChat.refer">
				</input>
				<button class="cu-btn bg-green shadow" @click="sendMsg">发送</button>
			</view>
		</view>
	</view>
	<view v-else class="cu-modal bottom-modal show" :style="[{top:'auto'},{right:'auto'}]">
		<view class="cu-dialog">
			<view class="cu-bar input">
				<view class="action">
					<text class="cuIcon-fold text-grey" @click="msgFold"></text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {genUUID, WsClient} from './websock.js';
	export default {
		name: 'Aij',
		data() {
			return {
				aijShow: true,
				aijChat: {
					msg: '你好',
					password: false,
					refer: '',
					placeholder: '请输入消息',
					pop: {},
					word: '',
					focus: true,
				},
				aijMsgs: [],
				aijConf: {
					wsServer: 'ws://192.168.0.101:9001/ws',
					wsAccount: '',
					wsSecret: '',
					pushServer: 'ws://192.168.0.101:2700',
					liveServer: 'http://192.168.0.101:8080/live/',
					liveDelay: 2500,
				},
				wsClient: null,
				sessionId: genUUID(),
				liveClient: null,
				flvPlayer: null,
				flvAudio: null,
				scrollTop: 0,
			}
		},
		mounted() {
			window.clickMsg = this.clickMsg;
			this.aijShow = true;
			var that = this;
			//等待页面渲染完成
			setTimeout(function(){
				that.checkLogin();
			}, 1000);
		},
		methods: {
			inputFocus () {
				this.aijChat.focus = true;
				this.aijChat.placeholder = "";
			},
			inputBlur () {
				this.aijChat.focus = false;
				this.aijChat.placeholder = "请输入消息";
			},
			msgFold () {
				this.aijShow = this.aijShow ? false : true;
			},
			msgScroll () {
				const scrollHeight = this.aijMsgs.length * 20;
				this.scrollTop = scrollHeight;
			},
			//连接服务
			connWs(wsServer, onSucess = null, onError = null) {
				var that = this;
				var client = new WsClient({
					login: this.aijConf.wsAccount,
					passwd: this.aijConf.wsSecret,
					socketUrl: this.aijConf.wsServer,
					sessid: this.sessionId,
					onmessage: function(e) {
						that.handleMsg(e.eventData);
					},
					onWSConnect: function(o) {
						client.call('login', {});
						if (onSucess) onSucess();
					},
					onWSLogin: function(success) {
					},
					onWSError: function(e) {
						if (onError) onError(e);
					},
					onWSClose: function(success) {
					}
				});
				return client;
			},
			//检查登录
			checkLogin() {
				var labels = document.querySelectorAll('.uni-tabbar__label');
				var txt = labels && labels.length == 3 ? labels[2].innerText : '';
				if (txt == "我的") {
					this.initMsg('我已成功登录会员');
				} else {
					this.initMsg('你好');
				}
				this.sendMsg();
			},
			//初始化消息
			initMsg(msg) {
				this.aijChat.pop = {visible: false};
				this.aijChat.refer = '';
				this.aijChat.password = false;
				this.aijChat.placeholder = '请输入消息';
				this.aijChat.msg = msg;
				this.inputFocus();
			},
			//处理消息
			procMsg(msg, txt = '') {
				var pattern = /[，。！？：；、,.!?:;]/;
				var msgs = msg.split(pattern);
				if (msgs.length <= 1) return;
				var txts = txt.split(pattern);
				msgs[0] = txts[txts.length - 1] + msgs[0];
				var len = msgs.length;
				for (var i = 0; i < len - 1; i++) {
					var sub = msgs[i] + ",";
					//console.log(sub);
					if (this.liveClient) {
						var params = {
							body: sub
						};
						this.liveClient.call("message", params, function(e) {
						}, function(e) {
						});
					}
				}
			},
			//点击消息
			clickMsg(event) {
				var txt = '';
				if (event.target.node) {
					const eleType = event.target.node.name;
					const children = event.target.node.children;
					if (eleType != 'a' || children.length <= 0) return;
					txt = children[0].text;
				} else {
					txt = event.innerText;
				}
				//console.log(txt);
				var ele = document.querySelector('[aij="' + txt + '"]');
				if (ele) {
					var tagName = ele.tagName.toLowerCase();
					if (tagName == 'a' || tagName == 'uni-button') {
						ele.click();
						this.initMsg('我要' + txt);
						this.sendMsg();
					} else if (tagName == 'uni-view') {
						this.initMsg('我要' + txt);
						this.sendMsg();
					} else if (tagName == 'uni-input') {
						var input = ele.querySelector('input');
						var tagType = input.getAttribute('type');
						this.aijChat.pop = '';
						this.aijChat.password = tagType == 'password' ? true : false;
						this.aijChat.msg = input.value;
						this.aijChat.refer = txt;
						this.aijChat.placeholder = '请' + txt;
						this.inputFocus();
					}
				}
			},
			//解析消息
			parseMsg(msg) {
				if (msg.indexOf(']') >= 0) {
					msg = msg.replaceAll('[', '<a href="javascript:;" onclick="clickMsg(this)">');
					msg = msg.replaceAll(']', '</a>');
				}
				return msg;
			},
			//接收消息
			recvMsg(msg, id) {
				var msgHead = "<b>AI：</b>";
				var idMsg = null;
				this.aijMsgs.forEach(function (aijMsg) {
				    if (aijMsg.id === id) {
				        idMsg = aijMsg;
						return;
				    }
				});
				if (idMsg) {
					var txt = idMsg.msg;
					idMsg.msg = txt + msg;
					this.procMsg(msg, txt);
				} else {
					idMsg = {
						  id: id,
						  type: 'you',
						  msg: msgHead + msg,
					};
					this.aijMsgs.push(idMsg);
					this.procMsg(idMsg.msg);
				}
				if (msg == '') {
					var txt = idMsg.msg;
					idMsg.msg = this.parseMsg(txt);
					//this.saveMsg(txt, 'aij', 0);
				}
				this.$nextTick(() => {
					this.msgScroll();
				});
				if (msg == '' && idMsg.msg.endsWith('登录会员完成。')) {
					var that = this;
					//等待页面渲染完成
					setTimeout(function(){
						that.checkLogin();
					}, 1000);
				}
			},
			//处理消息
			handleMsg(data) {
				if (data.method == "message") {
					this.recvMsg(data.params.body, data.id);
				}
				if (data.method == "word") {
					setTimeout(function() {
						this.aijChat.word = data.params.body;
					}, liveDelay);
				}
			},
			//发送消息
			sendMsg() {
				if (!this.wsClient) {
					var that = this;
					this.wsClient = this.connWs(this.wsServer, function(e) {
						that.sendMsg();
					}, function(e) {
						that.wsClient = that.connWs(that.wsServer);
					});
					return;
				}
				var refer = this.aijChat.refer;
				if (refer) {
					var ele = document.querySelector('[aij="' + refer + '"]');
					if (!this.aijChat.pop) {
						var input = ele.querySelector('input');
						input.value = this.aijChat.msg;
						//必须手动触发事件同步
						input.dispatchEvent(new Event('input'));
					}
					this.initMsg('我已' + refer);
				}
				if (!this.aijChat.msg) {
					this.inputFocus();
					return;
				}
				var params = {
					body: this.aijChat.msg
				};
				var webClient = this.wsClient.socketReady() ? this.wsClient : this.liveClient;
				if (webClient) {
					var that = this;
					webClient.call("message", params, function(e) {
						var msgHead = "<b>我：</b>";
						var msg = {
							  type: 'me',
							  msg: msgHead + that.aijChat.msg,
						};
						that.aijMsgs.push(msg);
						that.aijChat.msg = '';
						that.$nextTick(() => {
							that.msgScroll();
						});
					}, function(e) {
					});
				}
			},
			//保存消息
			saveMsg(msg, from, count, self) {
			},
			//加载消息
			loadMsg(from) {
			},
			//显示消息
			showMsg() {
			},
			//视频开关
			openVideo() {
			  
			}
		}
	}
</script>

<style>
	.rich-text>>>a {
		cursor: pointer;
		text-decoration: underline;
	}
	.scroll-y {
		height: 20px;
	}
</style>
